package com.example.app.components.MyPlaceSelected

import android.content.Context
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.LocationOn
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.amap.api.location.AMapLocation
import com.amap.api.maps.AMap
import com.amap.api.maps.model.LatLng
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.core.PoiItemV2
import com.amap.api.services.poisearch.PoiResultV2
import com.amap.api.services.poisearch.PoiSearchV2
import com.example.app.components.MyEmptyShow.MyEmptyTextShow
import com.example.app.components.MyIcon.MyIcon
import com.example.app.components.MyListItem.MyListItem
import com.example.app.components.MySpacer.MySpacer
import com.example.app.components.MyText.MyText
import com.example.app.components.MyTextField.MySearchTextField
import com.example.app.components.MyTip.MyTipType
import com.example.app.pages.main.mainTipState
import com.example.app.ui.theme.my_description_color
import com.example.app.ui.theme.shapeLarge

//开始搜索
fun searchPlaceHandler(text: String,
    latLng: LatLng?,
    context: Context,
    suggestionsList: MutableList<PoiItemV2>,
    emitFromSearchPlaceHandler:(suggestionsList: MutableList<PoiItemV2>)->Unit
) {
    var query = PoiSearchV2.Query(
        text,
        "",
        ""
    )

    query.let {
        it.pageSize = 20
        it.location = LatLonPoint(
            latLng!!.latitude,
            latLng!!.longitude
        )
    }
    //搜索建议
    var poiSearchV2 = PoiSearchV2(
        context,
        query
    )

    poiSearchV2.setOnPoiSearchListener(object :
        PoiSearchV2.OnPoiSearchListener {
        override fun onPoiSearched(
            p0: PoiResultV2?,
            p1: Int
        ) {
            if (p1 == 1800) {
                mainTipState.show(
                    description = "账号维度日调用量超出限制",
                    type = MyTipType.FAIL,
                    title = "USER_DAILY_QUERY_OVER_LIMIT"
                )
            } else {
                suggestionsList.clear()
                if (p0 != null && p0.pois != null && p0.pois.size > 0) {
                    suggestionsList.addAll(p0.pois)
                }
                emitFromSearchPlaceHandler(suggestionsList)
            }
        }

        override fun onPoiItemSearched(
            p0: PoiItemV2?,
            p1: Int
        ) {
            TODO("Not yet implemented")
        }
    })
    //开始搜索
    poiSearchV2.searchPOIAsyn()
}
@Composable
fun MapSearchSuggestsView(

    //父传子的属性，父亲只把变量传入子，子负责把这个函数去实现
    props: ((mapInstance: AMap?, curLatLng: LatLng?, aMapLocation: AMapLocation?, suggestionsList: MutableList<PoiItemV2>) -> Unit) -> Unit,
    //子传父
    emitsFromMapSearchSuggestsView: (latLng: LatLng?, title: String?) -> Unit
) {
    var context = LocalContext.current
    var _suggestionsList = remember {
        mutableStateListOf<PoiItemV2>()
    }
    var textFieldValue by remember {
        mutableStateOf(TextFieldValue(""))
    }
    var imePadding = WindowInsets.ime.asPaddingValues()
        .calculateBottomPadding()
    var windowHeight = with(LocalDensity.current.density) {
        LocalConfiguration.current.screenHeightDp.dp
    }
    var expandHeightState =
        animateDpAsState(targetValue = if (imePadding > 0.dp) windowHeight * .6f else windowHeight * .5f)

    Column(
        modifier = Modifier
            .clip(RoundedCornerShape(topStart = shapeLarge,
                topEnd = shapeLarge,
                bottomEnd = 0.dp,
                bottomStart = 0.dp))
            .background(MaterialTheme.colorScheme.surface)
            .height(expandHeightState.value)
    ) {
        MySpacer(modifier = Modifier.height(8.dp))
        //搜索框
        MyListItem(
            headlineContent = {
                MySearchTextField(
                    showCancelBtn = false,
                    hasPadding = false,
                    props = ({
                        it(textFieldValue)
                    }),
                    emitsFromMySearchTextField = {
                        textFieldValue = it
                        if (!it.text.isEmpty()) {
                            props({ mapInstance, curLatLng, aMapLocation, suggestionsList ->
                                _suggestionsList.clear()
                                _suggestionsList.addAll(suggestionsList)
                                //开始搜索
                                searchPlaceHandler(text = it.text!!,
                                    latLng = curLatLng,
                                    context = context,
                                    suggestionsList = suggestionsList,
                                    emitFromSearchPlaceHandler = {suggestionsList ->
                                        _suggestionsList.clear()
                                        _suggestionsList.addAll(suggestionsList)
                                    }
                                )
                            })
                        } else {
                            //清空搜索框
                            emitsFromMapSearchSuggestsView(
                                null,
                                null
                            )
                        }
                    })
            })
        //搜索提示列表
        Box {
            if (_suggestionsList.size > 0) {
                LazyColumn {
                    itemsIndexed(_suggestionsList) { index, item ->
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable {
                                    textFieldValue = TextFieldValue(
                                        item.title,
                                        TextRange(item.title.length)
                                    )
                                    var _latLng = LatLng(
                                        item.latLonPoint.latitude,
                                        item.latLonPoint.longitude
                                    )
                                    //点击
                                    emitsFromMapSearchSuggestsView(
                                        _latLng,
                                        item.title
                                    )
                                    //不清空提示列表
                                    //suggestionsList.clear()
                                }
                        ) {
                            MyListItem(
                                trailingContent = {
                                },
                                modifier = Modifier.clip(
                                    RectangleShape
                                ),
                                hasWrap = true,
                                myListItemWrapColumnBackgroundColor = Color.Transparent,
                                leadingContent = {
                                    MyIcon(imageVector = Icons.Rounded.LocationOn)
                                },
                                headlineContent = {
                                    MyText(text = item.title)
                                },
                                supportingContent = {
                                    MyText(
                                        text = item.snippet,
                                        style = MaterialTheme.typography.bodySmall.copy(
                                            fontSize = 12.sp,
                                            color = my_description_color
                                        )
                                    )
                                }
                            )
                        }
                    }
                }
            } else {
                Row(
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    MyEmptyTextShow(
                        marginTopDp = 50.dp,
                        descriptionText = "请输入搜索内容"
                    )
                }
            }
        }
    }
}
